package com.light.gulimall.coupon.service.impl;

import com.light.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.light.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;

import com.light.gulimall.coupon.dao.SeckillSessionDao;
import com.light.gulimall.coupon.entity.SeckillSessionEntity;
import com.light.gulimall.coupon.service.SeckillSessionService;
import org.springframework.util.CollectionUtils;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLasted3SeckillInfo() {
        QueryWrapper<SeckillSessionEntity> queryWrapper = new QueryWrapper<>();

        // 获取当天的 00:00:00
        LocalDateTime startTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        // 获取两天后的 23:59:59
        LocalDateTime endTime = startTime.plusDays(2).withHour(23).withMinute(59).withSecond(59);

        // 添加 between 查询条件
        queryWrapper.between("start_time", startTime, endTime);
        List<SeckillSessionEntity> seckillSessionEntities = list(queryWrapper);
        if (!CollectionUtils.isEmpty(seckillSessionEntities)) {
            return seckillSessionEntities.stream().peek(seckillSessionEntity -> {
                Long id = seckillSessionEntity.getId();
                List<SeckillSkuRelationEntity> list = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", id));
                seckillSessionEntity.setSkuRelationEntities(list);
            }).collect(Collectors.toList());
        }
        return null;
    }

}